<template>
  <div class="rightPanel">
    <div class="page">
      <div class="item-prop-panel">
        <div v-if="props != null && props.item != null" class="rp-label">
          <!-- {{ props.item.erp_id + "-" + props.item.object_name }} -->
          {{ props.item.erp_id }}
        </div>
        <div v-else class="rp-label">Unknow</div>
        <div class="rp-content">
          <div class="rp-content-a">
            <div class="item-image-border">
              <img
                v-if="props.item != null && props.item.icon != null"
                :src="props.item.icon"
                alt=""
                class="item-img"
              />
              <img v-else src="" alt="" class="item-img" />
            </div>
            <div class="item-prop-list">
              <li v-for="prop in baseProps" :key="prop.displayName">
                <div class="item-prop-col">
                  <div class="item-base-prop">{{ prop.displayName }} :</div>
                  <div class="item-base-prop">
                    <!-- {{ props.item[prop.realPropName] }} -->
                    {{ getPropValue(prop) }}
                  </div>
                </div>
              </li>
            </div>
          </div>
          <div class="rp-content-b">
            <!-- <el-descriptions
              :column="1"
              size="Default"
              direction="horizontal"
              style="margintop: 24px"
            >
              <el-descriptions-item label="基准价格">A</el-descriptions-item>
              <el-descriptions-item label="加工工时">B</el-descriptions-item>
              <el-descriptions-item label="供应商">C</el-descriptions-item>
            </el-descriptions> -->
            <div v-if="isSearching || priceInfo == null">
              <el-skeleton :rows="4" />
            </div>
            <div v-else>
              <div class="item-price-prop-list">
                <div class="item-prop-col">
                  <div class="item-base-prop">总成本 :</div>
                  <div class="item-base-prop">
                    {{ priceInfo ? priceInfo.KEPH_SUM.toFixed(2) + "￥" : "" }}
                  </div>
                </div>
                <div class="item-prop-col">
                  <div class="item-base-prop">人工工时 :</div>
                  <div class="item-base-prop">
                    {{ priceInfo ? priceInfo.humanHour : "" }}
                  </div>
                </div>
                <div class="item-prop-col">
                  <div class="item-base-prop">机器工时 :</div>
                  <div class="item-base-prop">
                    {{ priceInfo ? priceInfo.machineHour : "" }}
                  </div>
                </div>
                <div class="item-prop-col">
                  <div class="item-base-prop">供应商 :</div>
                  <div class="item-base-prop">
                    {{ priceInfo ? priceInfo.vendor_name : "" }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="item-prop-panel">
        <div class="rp-label">价格成分</div>
        <!-- <div class="chart-panel">
            <div id="pieChart" style="width: 100%; height: 380px"></div>
          </div> -->
        <div id="pieChart" style="width: 99%; height: 300px"></div>
      </div>
      <div class="item-prop-panel">
        <div class="rp-label">基准价格[CNY/PCS]</div>
        <!-- <div class="chart-panel">
            <div id="basePrice" style="width: 100%; height: 380px"></div>
          </div> -->
        <div id="basePrice" style="width: 99%; height: 300px"></div>
      </div>
      <div class="item-prop-panel">
        <div class="rp-label">基准价格[CNY/PCS]</div>
        <table
          class="price-table"
          style="width: 99%; height: 200px; border-collapse: collapse"
        >
          <tbody>
            <tr
              v-for="(item, index) in priceTableData"
              :key="item.id"
              :class="{ divider: index === 2 }"
            >
              <td style="text-align: left; flex: 3">{{ item.name }}</td>
              <td style="text-align: right; flex: 1">{{ item.value }}</td>
              <td style="text-align: right; flex: 1">{{ item.percent }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!-- <div class="bottom-button-panel">
      <button class="button">查看结构成本</button>
    </div> -->
  </div>
</template>

<script>
import * as echarts from "echarts";
import elementResizeDetectorMaker from "element-resize-detector";

// import { Vue3SeamlessScroll } from "vue3-seamless-scroll";
// import progressBar from "./progressBar.vue";

export default {
  data() {
    return {
      isSearching: false,
      baseProps: [
        { displayName: "ITEM DISC", realPropName: "object_name" },
        { displayName: "描述", realPropName: "object_desc" },
        { displayName: "发布状态", realPropName: "statusName" },
        { displayName: "发布日期", realPropName: "releasedDate" },
        { displayName: "有效性" },
      ],
      priceProps: [
        { displayName: "基准价格", value: "11.71" },
        { displayName: "加工工时", value: "5h" },
        { displayName: "供应商", value: "富土康2号流水线" },
      ],
      priceInfo: null,
      selectedItem: null,
      searchText: "",
      selectedOption: "",
      itemImage:
        "https://img2.baidu.com/it/u=1934300084,1837891739&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=666",
      testData: [2000, 1500, 500, 2200],
      priceTableData: [
        { name: "原材料", value: 0, percent: "0%" },
        { name: "制造", value: 0, percent: "0%" },
        { name: "折旧", value: 0, percent: "0%" },
        { name: "其它费用", value: 0, percent: "0%" },
        { name: "汇总", value: 0, percent: "0%" },
      ],
      priceBarColNames: ["其它费用", "折旧", "制造", "原材料"],
      priceBarValues: [0, 0, 0, 0],
      pieDatas: [
        { value: 0, name: "基准价格" },
        { value: 0, name: "其它费用" },
      ],
    };
  },
  mounted: function () {
    //this.initPieChart("pieChart2");
    this.initPieChart("pieChart"); // 页面加载完成后调用初始化函数
    this.initBar("basePrice");
    if (this.uid != null && this.uid.length > 0) {
      this.loadPartPrice();
    }
    this.$emit("setMultiSelect", false);
  },
  created() {
    watch(
      () => this.uid,
      (newUid, oldUid) => {
        console.log("uid =>", newUid, oldUid);
        this.loadPartPrice();
      }
    ),
      watch(
        () => this.activeName,
        (newName, curName) => {
          console.log("newName ==>" + newName);
          if (newName == this.paneName) {
            this.loadPartPrice();
          }
        }
      );
  },
  methods: {
    setPriceTableData(name, value, sumValue) {
      const p = ((value / sumValue) * 100).toFixed(0) + "%";
      const index = this.priceTableData.findIndex((item) => item.name === name);
      if (index < 0) return;
      this.priceTableData[index].value = value;
      this.priceTableData[index].percent = p;
    },
    calculateReportData(data) {
      let materialPrice, manufacturePrice, deprecition, otherPrice, sum;
      materialPrice = data.KEPH_KST001_UNIT?.toFixed(2);
      manufacturePrice = data.KEPH_MANUFACTURE?.toFixed(2);
      deprecition = data.KEPH_DEPRECITION?.toFixed(2);
      otherPrice = data.KEPH_OTHER?.toFixed(2);
      sum = data.KEPH_SUM?.toFixed(2);
      this.priceBarValues = [
        otherPrice,
        deprecition,
        manufacturePrice,
        materialPrice,
      ];
      this.setPriceTableData("原材料", materialPrice, sum);
      this.setPriceTableData("制造", manufacturePrice, sum);
      this.setPriceTableData("折旧", deprecition, sum);
      this.setPriceTableData("其它费用", otherPrice, sum);
      this.setPriceTableData("汇总", sum, sum);
      this.pieDatas[0].value = (
        data.KEPH_KST001 +
        data.KEPH_MANUFACTURE +
        data.KEPH_DEPRECITION
      )?.toFixed(2);
      this.pieDatas[1].value = otherPrice;
      this.initBar("basePrice");
      this.initPieChart("pieChart");
    },
    loadPartPrice() {
      console.log("查询价格信息");
      this.isSearching = true;
      const url = "/getPartPriceByUid?uid=" + this.uid;
      this.$http
        .get(url)
        .then((response) => {
          console.log(response.data);
          this.priceInfo = response.data;
          this.isSearching = false;
          this.calculateReportData(response.data);
        })
        .catch((error) => {
          this.isSearching = false;
          console.log(error);
        });
    },
    getPropValue(prop) {
      //console.log(this.item, prop);
      const propName = prop.realPropName;
      return this.item == null ? "" : this.item[propName];
    },
    initBar(elementName) {
      const chartDom = document.getElementById(elementName); // 获取DOM元素

      const myChart = echarts.init(chartDom); // 初始化echarts对象

      chartDom.setAttribute("_echarts_instance_", ""); //将生成的图标ID清除掉，让每次切换路由都能更新

      const option = {
        // title: {
        //   text: "",
        // },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {},
        grid: {
          left: "3%",
          right: "4%",
          top: "1%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          boundaryGap: [0, 0.01],
        },
        yAxis: {
          type: "category",
          data: this.priceBarColNames,
        },
        series: [
          {
            label: {
              show: true,
              position: "auto",
              formatter: function (params) {
                return " " + params.value + "￥";
              },
            },
            type: "bar",
            data: this.priceBarValues,
          },
        ],
      };
      myChart.setOption(option, true); // 设置配置项并显示图表
      let erd = elementResizeDetectorMaker();
      //动态适应父项DIV的宽度变化
      erd.listenTo(document.getElementById(elementName), () => {
        nextTick(() => {
          myChart.resize();
        });
      });
    },
    initPieChart(elementName) {
      const chartDom = document.getElementById(elementName); // 获取DOM元素

      if (chartDom == null || chartDom == undefined) return;

      const myChart = echarts.init(chartDom); // 初始化echarts对象

      chartDom.setAttribute("_echarts_instance_", ""); //将生成的图标ID清除掉，让每次切换路由都能更新

      const option = {
        legend: {
          bottom: "0%",
          left: "center",
        },
        tooltip: {
          trigger: "item",
        },
        series: [
          {
            name: "费用",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "outside",
              formatter: function (params) {
                return params.name + ": " + params.value + "￥";
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "20",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: true,
            },
            data: this.pieDatas,
          },
        ],
      };

      myChart.setOption(option);

      let erd = elementResizeDetectorMaker();

      //动态适应父项DIV的宽度变化
      erd.listenTo(document.getElementById(elementName), () => {
        nextTick(() => {
          myChart.resize();
        });
      });
    },
  },
};
</script>

<script setup>
import { nextTick, ref, defineProps, defineExpose, watch } from "vue";

const data = ref([
  { value: 67, name: "A" },
  { value: 40, name: "B" },
  { value: 120, name: "C" },
  { value: 58, name: "D" },
  { value: 85, name: "E" },
]);

setInterval(() => {
  data.value = data.value.map((item) => ({
    ...item,
    value: Math.random() * 100,
  }));
}, 1000);

let props = defineProps({
  uid: ref(),
  item: ref(),
  paneName: ref(),
  activeName: ref(),
});

function refresh() {
  // this.$options.methods.loadPartPrice.call(this);
  // this.initPieChart("pieChart"); // 页面加载完成后调用初始化函数
  // this.initBar("basePrice");
  this.$options.methods.initPieChart.call("pieChart");
}

defineExpose({
  refresh,
});
</script>

<style scoped>
.chart {
  height: 400px;
}
</style>

<style>
.rightPanel {
  /* flex: 0 0 80%; */
  flex: 5;
  background-color: white;
}

.page {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 15px;
}

.item-prop-panel {
  border: 1px solid #ccc;
  padding: 10px;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  width: auto;
}
.chart-panel {
  /* border: 1px solid #ccc; */
  padding: 10px;
  display: flex;
  justify-content: center;
  width: 80%;
  height: 100%;
}

.rp-label {
  background-color: gainsboro;
  height: 30px;
  margin-bottom: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.rp-content {
  background-color: white;
  display: flex;
  flex-direction: column;
  justify-content: start;
}

.rp-content-a {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  background-color: white;
}

.rp-content-b {
  margin-top: 20px;
}

.item-img {
  height: 100px;
  width: 100px;
}

.item-image-border {
  border-style: solid;
  border-color: grey;
  border-width: 1px;
  height: 120px;
  width: 240px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item-prop-list {
  margin-left: 20px;
  display: flex;
  justify-content: start;
  align-items: space-between;
  flex-direction: column;
  gap: 4px;
  flex: 1;
  white-space: nowrap;
}

.item-base-prop {
  font-size: 15px;
}

.item-prop-col {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.item-price-prop-list {
  display: flex;
  justify-content: start;
  align-items: space-between;
  flex-direction: column;
  gap: 4px;
}

.price-table {
  width: 100%;
  table-layout: fixed;
  border-collapse: collapse;
}

.resizer {
  top: 0;
  right: 0;
  width: 2px;
  /* height: 90vh;  */
  bottom: 0;
  background-color: #ccc;
  cursor: col-resize;
}
.bottom-button-panel {
  margin-top: 20px;
  display: flex;
  justify-content: right;
}
</style>
